<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@ page import="java.util.*, social.*, QuizPackage.*,java.sql.*,java.text.*,java.util.Date"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<%
int quizid;
if (request.getParameter("quizid")==null) {
	quizid = Integer.parseInt((String)request.getAttribute("quizid"));
} else {
	quizid = Integer.parseInt((String)request.getParameter("quizid"));
}

Quiz quiz = new Quiz(quizid);
out.println("<title>"+quiz.getName()+"</title>");
%>

</head>
<body>


<%

	String username = (String) session.getAttribute("username");

	SocialDBC db = (SocialDBC) request.getServletContext()
			.getAttribute("database");
	QuizDBC qdb = (QuizDBC) request.getServletContext().getAttribute(
			"quizDatabase");
	
	String profile = (String) request.getParameter("profileName");
	String profileName;
	if (profile == null) {
		profileName = (String) session.getAttribute("profileName");
	} else {
		profileName = profile;
	}
	
	if (username == null || profileName == null) {
		out.println("<div id=\"header\" style=\"background-color: #3B5998; color: white; font: Tahoma \">");
		out.println("<h1 style=\"margin-bottom: 0; text-align: center;\">");
		out.println("<img src=\"Nuvola_apps_korganizer.png\" alt=\"Smiley face\" height=\"45\" width=\"45\" />");
		out.println("QuizSite");
		out.println("</h1>"); 
		out.println("</div>");
		out.println("<h1 style=\"text-align: center; background-color: #FDEEF4\">");
		out.println(quiz.getName());
		out.println("</h1>");
		out.println("<div id=\"buffer\"");
		out.println("style=\"background-color: #FFFFFF; width: 100%; height: 20px; float: left\">");
		out.println("</div>");
		session = request.getSession();
		session.setAttribute("" + quizid,quiz);
	
		out.println("<div style=\"float: left; width: 30%\">");
		out.println("<p><b>Description:</b> "+quiz.getDescription()+"</p>");
		out.println("<b>Creator:</b> <a href=\"user-profile.jsp?profileName="+quiz.getCreator()+"\">"+quiz.getCreator()+"</a>");

		QuizDBC dbc = new QuizDBC();
		ResultSet rs = dbc.getQuiz(quizid);
		try {
			rs.next();
			out.println("<p><b>Category:</b> "+rs.getString("category")+"</p>");
		} catch (SQLException e2) {
			e2.printStackTrace();
		}

		out.print("<p><b>Tags:</b> ");
		rs = dbc.getTags(quizid);
		try {
			while(rs.next())
			{
				out.print("<a href=\"quizList.jsp?tag="+rs.getString("tag")+"\">"+rs.getString("tag")+"</a>  ");
				//out.print(rs.getString("tag")+",");
			}
		} catch (SQLException e2) {
			e2.printStackTrace();
		}
		out.println("</p>");

		out.println("<p></p>");

		out.println("<p>Average rating: "+qdb.averageRating(quizid)+"</p>");

		rs = dbc.getResults(quizid);
		int totalScore=0;
		int numResults=0;
		int totalTime=0;
		int total=-1;
		try {
			while(rs.next())
			{
				totalScore += Integer.parseInt(rs.getString("score"));
				totalTime += Integer.parseInt(rs.getString("length"));
				numResults++;
				if(total==-1) total = Integer.parseInt(rs.getString("total"));
			}
		} catch (NumberFormatException e1) {
			e1.printStackTrace();
		} catch (SQLException e1) {
			e1.printStackTrace();
		}
		double averageScore = ((double)totalScore)/numResults;
		double averageTime = ((double)totalTime)/numResults;
		DecimalFormat df = new DecimalFormat("#.##");

		//Back to homepage
		out.println("<div id=\"button\"style=\"background-color: #FFFFFF; width: 100%; float: left\">");
		out.println("<form method = \"post\" action = \"homepage.jsp\">");
		out.println("<input type = \"submit\" value =\"Back to Homepage\"/>");
		out.println("</form>");
		out.println("</div>");
		
		out.println("</div>");
		out.println("<div style=\"float: left; width: 30%; background-color: #EEEEEE\">");
		if(total!=-1)
		{
			out.println("<p><b>Average Score:</b> "+df.format(averageScore)+"/"+total+"</p>");
			out.println("<p><b>Average Time:</b> "+df.format(averageTime)+" seconds</p>");
		}else{
			out.println("<p><b>Average Score:</b> -</p>");
			out.println("<p><b>Average Time:</b> -</p>");
		}

		rs = dbc.getTopPerformers(quizid);
		out.println("<p><b>All Time Top Performers</b></p>");
		out.println("<ul>");
		int count=0;
		try {
			while(rs.next() && count<5)
			{
				out.print("<li><a href=\"user-profile.jsp?profileName="+rs.getString("userID")+"\">"+rs.getString("userID")+"</a>");
				out.println(" <b>Score:</b> "+rs.getString("score")+"/"+rs.getString("total")+"   <b>Time:</b>  "+rs.getString("length")+" seconds</a></li>");
				count++;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		out.println("</ul>");

		rs = dbc.getTopPerformers(quizid);
		out.println("<p><b>Today's Top Performers</b></p>");
		count=0;
		Date date = new Date();
		long now = date.getTime();
		try {
			out.println("<ul>");
			while(rs.next() && count<5)
			{
				if(Long.parseLong(rs.getString("timetaken")) > (now-Quiz.RECENT_TIME))
				{
					out.print("<li><a href=\"user-profile.jsp?profileName="+rs.getString("userID")+"\">"+rs.getString("userID")+"</a>");
					out.println(" <b>Score:</b> "+rs.getString("score")+"/"+rs.getString("total")+"   <b>Time:</b>  "+rs.getString("length")+" seconds</a></li>");
					count++;
				}
			}
			out.println("</ul>");
		} catch (SQLException e) {
			e.printStackTrace();
		}

		out.println("<p><b>Most recent results.</b></p>");
		out.println("<ul>");
		rs = dbc.getResults(quizid);
		count = 0;
		try {
			while(rs.next() && count<5)
			{
				out.print("<li><a href=\"user-profile.jsp?profileName="+rs.getString("userID")+"\">"+rs.getString("userID")+"</a>");
				out.println(" <b>Score:</b> "+rs.getString("score")+"/"+rs.getString("total")+"   <b>Time:</b>  "+rs.getString("length")+" seconds</a></li>");
				count++;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}

		out.println("</ul>");
		out.println("</div>");
		return;
	}

	out.println("<div id=\"container\">");
	out.println("<div id=\"header\"");
	out.println("style=\"background-color: #3B5998; color: white; font: Tahoma; width: 100%; float: center\">");
	out.println("<h1 style=\"margin-bottom: 0; text-align: center;\">");
 	//System.out.println(String.format("username:%s profileName:%s",
 			//username, profileName));

 	out.println("<img src=\"Nuvola_apps_korganizer.png\" alt=\"Smiley face\" height=\"45\" width=\"45\" />");
 	if (profileName.equals(username)) {
 		out.println(String.format(
 				"<style=\"text-align: center\"> Welcome %s!",
 				profileName));
 	} else {
 		out.println(String.format(
 				"<style=\"text-align: center\"> %s's Profile </br>",
 				profileName));
 	}
 %>
</h1>
</div>

<!-- Search Box -->
<div id="header"
	style="background-color: #3B5998; color: white; font: Tahoma">
<form method="post" action="SearchServlet"><input type="text"
	name="queryUser" /> <input type="submit" value="Search" /></form>
</div>

<div id="buffer"
	style="background-color: #3B5998; width: 100%; height: 10px; float: left">
</div>

<div id="buttonContainer"
	style="background-color: #3B5998; color: white; font: Tahoma">
<%
	//Log out button
	out.println("<div id=\"button\"style=\"background-color: #3B5998; width: 6%; float: left\">");
	out.println("<form action=\"LogoutServlet\" method=\"post\">"
			+ "<input type=\"submit\" value=\"Log out\"/> </form>");
	out.println("</div>");

	//Log out button
	out.println("<div id=\"button\"style=\"background-color: #3B5998; width: 8%; float: left\">");
	out.println("<form action=\"CreateQuiz.jsp\" method=\"post\">"
			+ "<input type=\"submit\" value=\"Create Quiz\"/> </form>");
	out.println("</div>");

	//Quiz List button
	out.println("<div id=\"button\"style=\"background-color: #3B5998; width: 7%; float: left\">");
	out.println("<form action=\"quizList.jsp\" method=\"post\">"
			+ "<input type=\"submit\" value=\"Quiz List\"/> </form>");
	out.println("</div>");

	out.println("<div id=\"button\"style=\"background-color: #3B5998; width: 7%; float: left\">");
	out.println("<form method = \"post\" action = \"mailbox.jsp\">");
	out.println("<input type = \"submit\" value =\"Mailbox\"/>");
	out.println("</form>");
	out.println("</div>");

	//<!-- Mailbox Link --> 
	if (profileName.equals(username)) {

		if (db.checkAdmin(username)) {
			//Back to profile button
			out.println("<div id=\"button\"style=\"background-color: #3B5998; width: 10%; float: left\">");
			out.println("<form method = \"post\" action = \"user-profile.jsp?profileName="
					+ username + "\">");
			out.println("<input type = \"submit\" value =\"Back to Profile\"/>");
			out.println("</form>");
			out.println("</div>");
		} else {
			out.println("<div id=\"button\"style=\"background-color: #3B5998; width: 72%; float: left\">");
			out.println("<form method = \"post\" action = \"user-profile.jsp?profileName="
					+ username + "\">");
			out.println("<input type = \"submit\" value =\"Back to Profile\"/>");
			out.println("</form>");
			out.println("</div>");
		}

	} else {
		//Back to profile button
		out.println("<div id=\"button\"style=\"background-color: #3B5998; width: 10%; float: left\">");
		out.println("<form method = \"post\" action = \"user-profile.jsp?profileName="
				+ username + "\">");
		out.println("<input type = \"submit\" value =\"Back to Profile\"/>");
		out.println("</form>");
		out.println("</div>");
	}
%> <%
	if (db.checkAdmin(username) && !profileName.equals(username)) {
		//Remove User Button
		out.println("<div id=\"button\"style=\"background-color: #3B5998; width: 10%; float: left\">");
		out.println(String
				.format("<form action=\"AdminServlet\" method=\"post\">"
						+ "<input type=\"submit\" value=\"Remove User\">"
						+ "<input name=\"action\" type=\"hidden\" value=\"removeUser\"/>"
						+ "<input name=\"userAction\" type=\"hidden\" value=\"%s\"/>"
						+ "</form>", profileName));
		out.println("</div>");

		out.println("<div id=\"button\"style=\"background-color: #3B5998; width: 52%; float: left\">");
		if (!db.checkAdmin(profileName)) {
			//Promote to Admin button
			out.println(String
					.format("<form action=\"AdminServlet\" method=\"post\">"
							+ "<input type=\"submit\" value=\"Promote to Admin\">"
							+ "<input name=\"action\" type=\"hidden\" value=\"promoteAdmin\"/>"
							+ "<input name=\"userAction\" type=\"hidden\" value=\"%s\"/>"
							+ "</form>", profileName));
			out.println("</div>");
		} else {

			//Remove Admin button
			out.println("<div id=\"button\"style=\"background-color: #3B5998; width: 59%; float: left\">");
			out.println(String
					.format("<form action=\"AdminServlet\" method=\"post\" float: right>"
							+ "<input type=\"submit\" value=\"Remove Admin\">"
							+ "<input name=\"action\" type=\"hidden\" value=\"removeAdmin\"/>"
							+ "<input name=\"userAction\" type=\"hidden\" value=\"%s\"/>"
							+ "</form>", profileName));
			out.println("</div>");
		}
		//out.println("</div>");
	}
	if (db.checkAdmin(username) && (profileName.equals(username))) {
		//Site Statistics button
		out.println("<div id=\"button\"style=\"background-color: #3B5998; width: 10%; float: left\">");
		out.println(String
				.format("<form action=\"statistics.jsp\" method=\"post\" float: right>"
						+ "<input type=\"submit\" value=\"Site Statistics\">"
						+ "</form>"));
		out.println("</div>");

		//Make announcement button
		out.println("<div id=\"button\"style=\"background-color: #3B5998; width: 52%; float: left\">");
		out.println(String
				.format("<form action=\"create-announcement.jsp\" method=\"post\" float: right>"
						+ "<input type=\"submit\" value=\"Make Announcement\">"
						+ "<input name=\"userAction\" type=\"hidden\" value=\"%s\"/>"
						+ "</form>", profileName));
		out.println("</div>");
	}
%>
</div>

<div id="buffer"
	style="background-color: #3B5998; width: 100%; height: 10px; float: left">
</div>
</div>

<h1 style="text-align: center; background-color: #FDEEF4""><%=quiz.getName()%>
</h1>

<div style="float: left; width: 10%">
<p></p>
</div>

<div style="float: left; width: 30%">
<%
session = request.getSession();
session.setAttribute("" + quizid,quiz);

out.println("<p><b>Description:</b> "+quiz.getDescription()+"</p>");
out.println("<b>Creator:</b> <a href=\"user-profile.jsp?profileName="+quiz.getCreator()+"\">"+quiz.getCreator()+"</a>");

QuizDBC dbc = new QuizDBC();
ResultSet rs = dbc.getQuiz(quizid);
try {
	rs.next();
	out.println("<p><b>Category:</b> "+rs.getString("category")+"</p>");
} catch (SQLException e2) {
	e2.printStackTrace();
}

out.print("<p><b>Tags:</b> ");
rs = dbc.getTags(quizid);
try {
	while(rs.next())
	{
		out.print("<a href=\"quizList.jsp?tag="+rs.getString("tag")+"\">"+rs.getString("tag")+"</a>  ");
		//out.print(rs.getString("tag")+",");
	}
} catch (SQLException e2) {
	e2.printStackTrace();
}
out.println("</p>");


out.println("<form action=\"QuestionServlet\" method=\"post\">");
out.println("<input name=\"quizid\" type =\"hidden\" value=\""+quizid+"\"/>");
out.println("<input type=\"submit\" name=\"submit\" value=\"Begin\">");
out.println("<input type=\"submit\" name=\"submit\" value=\"Practice Mode\">");
if(db.checkAdmin(username)) out.println("<input type=\"submit\" name=\"submit\" value=\"Review\">");
if(request.getParameter("done")!=null) out.println("Done reviewing.");
out.println("</form>");
%>

<form action="ChallengeServlet" method="post"><select
	name="friendName">
	<%

ArrayList<String> friendList = db.getFriendList(username);
for (int i=0; i<friendList.size(); i++) {
	String friendName = friendList.get(i);
	if (!db.challengeExists(friendName, username, quizid)) {
		out.println(String.format("<option value=\"%s\">%s</option>", friendName, friendName));
	}
}
%>
</select> <input name="quizid" type="hidden" value="<%out.print(quizid); %>" />
<input type="submit" value="Challenge" /></form>

<%

out.println("<p></p>");

out.println("<p>Average rating: "+qdb.averageRating(quizid)+"</p>");

out.println("<form action=\"RateQuizServlet\" method=\"post\">");
out.println("<input name=\"quizid\" type =\"hidden\" value=\""+quizid+"\"/>");
out.println("<input type=\"radio\" name=\"rate\" value=\"1\" /> 1 Star<br />");
out.println("<input type=\"radio\" name=\"rate\" value=\"2\" /> 2 Star<br />");
out.println("<input type=\"radio\" name=\"rate\" value=\"3\" /> 3 Star<br />");
out.println("<input type=\"radio\" name=\"rate\" value=\"4\" /> 4 Star<br />");
out.println("<input type=\"radio\" name=\"rate\" value=\"5\" / checked> 5 Star<br />");
out.println("<input type=\"submit\" value=\"Rate Quiz\"/>");
out.println("</form>");

out.println("<p></p>");

//REPORT QUIZ
out.println("<form action=\"ReportQuizServlet\" method=\"post\">");
out.println("<input name=\"quizid\" type =\"hidden\" value=\""+quizid+"\"/>");
out.println("<input type=\"submit\" value=\"Report\"/>");
out.println("</form>");

//DELETE QUIZ
if (db.checkAdmin(username)) {
	out.println("<p></p>");
	out.println("<form action=\"AdminServlet\" method=\"post\">");
	out.println("<input name=\"quizid\" type =\"hidden\" value=\""+quizid+"\"/>");
	out.println("<input type=\"submit\" value=\"Remove Quiz\"/>");
	out.println("<input type=\"hidden\" name=\"action\" value=\"removeQuiz\"/>");
	out.println("</form>");

	out.println("<p></p>");
	out.println("<form action=\"AdminServlet\" method=\"post\">");
	out.println("<input name=\"quizid\" type =\"hidden\" value=\""+quizid+"\"/>");
	out.println("<input type=\"submit\" value=\"Remove Result History\"/>");
	out.println("<input type=\"hidden\" name=\"action\" value=\"removeResults\"/>");
	out.println("</form>");
}

%>
</div>

<div style="float: left; width: 30%; background-color: #EEEEEE">
<%
rs = dbc.getResults(quizid);
int totalScore=0;
int numResults=0;
int totalTime=0;
int total=-1;
try {
	while(rs.next())
	{
		totalScore += Integer.parseInt(rs.getString("score"));
		totalTime += Integer.parseInt(rs.getString("length"));
		numResults++;
		if(total==-1) total = Integer.parseInt(rs.getString("total"));
	}
} catch (NumberFormatException e1) {
	e1.printStackTrace();
} catch (SQLException e1) {
	e1.printStackTrace();
}
double averageScore = ((double)totalScore)/numResults;
double averageTime = ((double)totalTime)/numResults;
DecimalFormat df = new DecimalFormat("#.##");

if(total!=-1)
{
	out.println("<p><b>Average Score:</b> "+df.format(averageScore)+"/"+total+"</p>");
	out.println("<p><b>Average Time:</b> "+df.format(averageTime)+" seconds</p>");
}else{
	out.println("<p><b>Average Score:</b> -</p>");
	out.println("<p><b>Average Time:</b> -</p>");
}

rs = dbc.getTopPerformers(quizid);
out.println("<p><b>All Time Top Performers</b></p>");
out.println("<ul>");
int count=0;
try {
	while(rs.next() && count<5)
	{
		out.print("<li><a href=\"user-profile.jsp?profileName="+rs.getString("userID")+"\">"+rs.getString("userID")+"</a>");
		out.println(" <b>Score:</b> "+rs.getString("score")+"/"+rs.getString("total")+"   <b>Time:</b>  "+rs.getString("length")+" seconds</a></li>");
		count++;
	}
} catch (SQLException e) {
	e.printStackTrace();
}
out.println("</ul>");

rs = dbc.getTopPerformers(quizid);
out.println("<p><b>Today's Top Performers</b></p>");
count=0;
Date date = new Date();
long now = date.getTime();
try {
	out.println("<ul>");
	while(rs.next() && count<5)
	{
		if(Long.parseLong(rs.getString("timetaken")) > (now-Quiz.RECENT_TIME))
		{
			out.print("<li><a href=\"user-profile.jsp?profileName="+rs.getString("userID")+"\">"+rs.getString("userID")+"</a>");
			out.println(" <b>Score:</b> "+rs.getString("score")+"/"+rs.getString("total")+"   <b>Time:</b>  "+rs.getString("length")+" seconds</a></li>");
			count++;
		}
	}
	out.println("</ul>");
} catch (SQLException e) {
	e.printStackTrace();
}

out.println("<p><b>Most recent results.</b></p>");
out.println("<ul>");
rs = dbc.getResults(quizid);
count = 0;
try {
	while(rs.next() && count<5)
	{
		out.print("<li><a href=\"user-profile.jsp?profileName="+rs.getString("userID")+"\">"+rs.getString("userID")+"</a>");
		out.println(" <b>Score:</b> "+rs.getString("score")+"/"+rs.getString("total")+"   <b>Time:</b>  "+rs.getString("length")+" seconds</a></li>");
		count++;
	}
} catch (SQLException e) {
	e.printStackTrace();
}

//out.println("</form>");
out.println("</ul>");


%>
</div>
</body>
</html>